<?php
	require_once(dirname(__FILE__) . "/../core/safeParam.php");
        require_once("../modules/facebook_phpSdk/src/facebook.php");
	
	define('FACEBOOK_APP_ID', '423263144390114');
	define('FACEBOOK_SECRET', '9d7e1f8c0dc393f3938bcc1d1595c19a');

	function parse_signed_request($signed_request, $secret) {
  		list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

  		// decode the data
  		$sig = base64_url_decode($encoded_sig);
  		$data = json_decode(base64_url_decode($payload), true);

  		if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
    			error_log('Unknown algorithm. Expected HMAC-SHA256');
    			return null;
  		}

  		// check sig
  		$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
  		if ($sig !== $expected_sig) {
    			error_log('Bad Signed JSON signature!');
    			return null;
  		}

  		return $data;
	}

	function base64_url_decode($input) {
    		return base64_decode(strtr($input, '-_', '+/'));
	}
	
	if ($_REQUEST) {
  	   $response = parse_signed_request($_REQUEST['signed_request'], FACEBOOK_SECRET);

	   $name 	= $response['registration']['name'];
	   $arrayName	= explode(' ', $name);
	  	
	   $nombre	= $arrayName[0];
	   $apellido	= $arrayName[1];
	   $email 	= $response['registration']['email'];
	   $celular 	= $response['registration']['celular'];
	   $direccion 	= $response['registration']['direccion'];
	   $username    = $response['registration']['username'];
	       	
	   //REGISTRO USUARIO DESDE FACEBOOK
	   $check_user_exists = $database->select("SELECT id FROM users where email = '" . $_POST['email'] . "'");
	   
	   if ($check_user_exists != FALSE) {
	   	$error .= $lang['reg_error_exists'];
	   	$smarty->assign("estado", 0);
	   	
  	   } else {
  	      $user = array();
    	      $user['name']      = $nombre;
    	      $user['last_name'] = $apellido;
    	      $user['email']     = $email;
    	      $user['phone']     = $celular; 
    	      $user['address']   = $direccion;
    	      $user['city']      = "Cordoba";
    	      $user['state']     = "Cordoba";
    	      $user['password']  = md5('987654321');
    		
    	      //insert user  
    	      $database->insert_array('users', $user);
    	      $_SESSION['userid'] = mysql_insert_id();

  	   }       		
	} else {
  		$smarty->assign("estado", 2);
	}
?>